#!/usr/bin/sh
echo "Code version file updater script"
echo "   by Alexey Prey Mulyukin (c) 2016"
echo "   email: alexprey@yandex.ru"
echo ""

VERSION_FILE=$1
CODE_VERSION_FILE=$2
CODE_PLACEHOLDER="1.0.0.0"
BUILD_NUMBER=$3

if [ -z $VERSION_FILE -a -z $CODE_VERSION_FILE ]; then
	echo "usage: sh updateVersion.sh VERSION_FILE CODE_VERSION_FILE [BUILD_NUMBER]"
	echo "   VERSION_FILE          file with target version value. Can contais a placeholder 'BUILD_NUMBER' for auto-updating"
	echo "   CODE_VERSION_FILE     file that should be updated with new version from VERSION_FILE and BUILD_NUMBER"
	echo "   BUILD_VERSION         build version"
	exit 1
fi

if [ ! -r $VERSION_FILE ]; then
	echo "Can't read '$VERSION_FILE'"
	echo "Version file should be readable!"
	exit 1
fi

if [ ! -r $CODE_VERSION_FILE ]; then
	echo "Can'r update '$CODE_VERSION_FILE'"
	echo "Code version file should be updatable!"
	exit 1
fi

if [ -z $BUILD_NUMBER ]; then
	echo "Build number parameter is not specified!"
	echo "Takes a default value '0'"
	BUILD_NUMBER=0
fi

echo "Version file:        '$VERSION_FILE'"
echo "Code version file:   '$CODE_VERSION_FILE'"
echo "Target build number: '$BUILD_NUMBER'"

TARGET_VERSION=`cat $VERSION_FILE | sed "s/BUILD_NUMBER/$BUILD_NUMBER/g"`
sed "s/$CODE_PLACEHOLDER/$TARGET_VERSION/g" $CODE_VERSION_FILE > $CODE_VERSION_FILE

echo "Update version file is successfully updated to $TARGET_VERSION"
